package com.xbongbong.saas.help.workflow;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkOrderErrorCodeEnum;
import com.xbongbong.pro.product.pojo.ProductSavePojo;
import com.xbongbong.pro.workorder.pojo.CreateNodeReturnPojo;
import com.xbongbong.saas.domain.entity.WorkOrderCcEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowNodeEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderPersonEntity;
import com.xbongbong.saas.domain.entity.WorkOrderProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.WorkOrderFlowNodeTypeEnum;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.WorkOrderStageRobTypeEnum;
import com.xbongbong.saas.enums.WorkOrderStageRuleEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.dictionary.WorkOrderShipStatusEnum;
import com.xbongbong.saas.help.SaasProductHelp;
import com.xbongbong.saas.model.WorkOrderCcModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import com.xbongbong.saas.model.WorkOrderPersonModel;
import com.xbongbong.saas.model.WorkOrderProductModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
public class WorkOrderHelp {

    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private UserModel userModel;
    @Resource
    private WorkOrderCcModel workOrderCcModel;
    @Resource
    private WorkOrderPersonModel workOrderPersonModel;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private WorkOrderProductModel workOrderProductModel;
    @Resource
    private SaasProductHelp saasProductHelp;


    public void createNewMain(Long workOrderId, String corpid, String userId) throws XbbException {
        if (corpid == null || userId == null) {
            return;
        }
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("workOrderId", workOrderId);
        params.put("isMain", 1);
        //删除现有主负责人
        workOrderFlowUserModel.delete(params);

        params.clear();
        params.put("corpid", corpid);
        params.put("workOrderId", workOrderId);
        params.put("userId", userId);
        params.put("isMain", 0);
        workOrderFlowUserModel.delete(params);

        params.clear();
        params.put("corpid", corpid);
        params.put("userId", userId);
        params.put("del", 0);
        List<UserEntity> userEntities = userModel.findEntitys(params);
        if (userEntities.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004);
        }

        UserEntity userEntity = userEntities.get(0);
        WorkOrderFlowUserEntity workOrderFlowUserEntity = new WorkOrderFlowUserEntity();
        workOrderFlowUserEntity.setCorpid(corpid);
        workOrderFlowUserEntity.setUserId(userEntity.getUserId());
        workOrderFlowUserEntity.setUserName(userEntity.getName());
        workOrderFlowUserEntity.setUserAvatar(userEntity.getAvatar());
        workOrderFlowUserEntity.setDataId(workOrderId);
        workOrderFlowUserEntity.setIsMain(1);
        workOrderFlowUserEntity.setDel(0);
        workOrderFlowUserModel.insert(workOrderFlowUserEntity);


    }


    public void saveCC(Long workOrderId, String corpid, JSONArray ccArray) throws XbbException {
        List<String> idIn = new ArrayList<>();
        for (Object object : ccArray) {
            JSONObject jsonObject = (JSONObject) object;
            String userId = jsonObject.getString("id");
            idIn.add(userId);
        }
        if (idIn.isEmpty()) {
            return;
        }
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("userIdIn", idIn);
        params.put("del", 0);
        List<UserEntity> userEntities = userModel.findEntitys(params);
        for (UserEntity entity : userEntities) {
            WorkOrderCcEntity workOrderCcEntity = new WorkOrderCcEntity();
            workOrderCcEntity.setCorpid(corpid);
            workOrderCcEntity.setWorkOrderId(workOrderId);
            workOrderCcEntity.setUserId(entity.getUserId());
            workOrderCcEntity.setUserName(entity.getName());
            workOrderCcEntity.setDel(0);
            workOrderCcModel.save(workOrderCcEntity);
        }

    }



    public CreateNodeReturnPojo createNode(WorkOrderEntity workOrderEntity, WorkOrderTemplateEntity workOrderTemplateEntity, WorkOrderStageEntity workOrderStageEntity) throws XbbException {
        String corpid = workOrderEntity.getCorpid();
        Long workOrderId = workOrderEntity.getId();
        Integer expectedTime = workOrderTemplateEntity.getExpectedTime();
        Boolean ifFree = Objects.equals(workOrderTemplateEntity.getIsFree(),1);
        Set<String> pushIdList = new HashSet<>();
        String userId = null;
        WorkOrderFlowNodeEntity workOrderFlowNodeEntity;
        boolean isRob = false;
        if (ifFree) {
            JSONObject dataJsonObj = workOrderEntity.getData();
            String managerId = dataJsonObj.getString(WorkOrderEnum.MANAGER_ID.getAttr());
            UserEntity userEntity = userModel.getByKey(managerId, corpid);
            if (userEntity == null) {
                throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222027);
            }
            //自由流程，直接根据前端选择的负责人生成node
            workOrderFlowNodeEntity = createNormalNode(workOrderId,expectedTime,userEntity,null);
            userId = userEntity.getUserId();
            pushIdList.add(userId);
        } else {
            //指定流程
            WorkOrderStageRuleEnum workOrderStageRuleEnum = WorkOrderStageRuleEnum.getByCode(workOrderStageEntity.getRuleId());
            expectedTime = workOrderStageEntity.getExpectedTime();
            if (workOrderStageRuleEnum == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            WorkOrderStageRobTypeEnum workOrderStageRobTypeEnum = WorkOrderStageRobTypeEnum.getByCode(workOrderStageEntity.getRefRobType());
            if (workOrderStageRobTypeEnum == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            switch (workOrderStageRuleEnum) {
                case SEND_TO_CLOSE:
                    params.put("corpid", corpid);
                    params.put("del", DelEnum.NORMAL.getDel());
                    params.put("tagIdJsonLike", Long.valueOf(workOrderStageEntity.getRefRobId()));
                    List<WorkOrderPersonEntity> personList = workOrderPersonModel.findEntitys(params);
                    if (personList == null || personList.size() ==  0) {
                        throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222014.getCode(), WorkOrderErrorCodeEnum.API_ERROR_222014.getMsg(), I18nMessageUtil.getMessage(I18nStringConstant.SERVICE));
                    }
                    //筛选最近的服务人员
                    JSONObject dataJsonObj = workOrderEntity.getData();
                    if (Objects.isNull(dataJsonObj)) {
                        throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222060);
                    }
                    JSONObject addressJsonObj = dataJsonObj.getJSONObject(WorkOrderEnum.ADDRESS.getAttr());
                    JSONObject locationJsonObj = null;
                    if (Objects.nonNull(addressJsonObj)) {
                        locationJsonObj = addressJsonObj.getJSONObject("location");
                    }
                    Double lon = 0D;
                    Double lat = 0D;
                    Double beeline = Double.MAX_VALUE;
                    if (locationJsonObj != null) {
                        lon = locationJsonObj.getDouble("lon");
                        lat = locationJsonObj.getDouble("lat");
                    }
                    WorkOrderPersonEntity workOrderPersonEntity = new WorkOrderPersonEntity();
                    for (WorkOrderPersonEntity personEntity : personList) {
                        Double distance = Math.pow(lon - personEntity.getLongitude(), 2) + Math.pow(lat - personEntity.getLatitude(), 2);
                        if (distance < beeline) {
                            workOrderPersonEntity = personEntity;
                            beeline = distance;
                        }
                    }
                    UserEntity userEntity = userModel.getByKey(workOrderPersonEntity.getUserId(),corpid);
                    if (userEntity == null) {
                        throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222027);
                    }
                    workOrderFlowNodeEntity = createNormalNode(workOrderId,expectedTime,userEntity,workOrderStageEntity);
                    userId = workOrderPersonEntity.getUserId();
                    pushIdList.add(userId);
                    break;
                case SEND_TO_LESS:
                    List<String> userIdList = new ArrayList<>();
                    String robTypeStr = workOrderStageRobTypeEnum.getName();
                    switch (workOrderStageRobTypeEnum) {
                        case USER:
                            break;
                        case SERVICE:
                            userIdList = getServiceUserIdList(corpid, workOrderStageEntity.getRefRobId());
                            break;
                        case DEPARTMENT:
                            userIdList = getDepartmentUserIdList(corpid, workOrderStageEntity.getRefRobId());
                            break;
                        default:
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                    if (userIdList.isEmpty()) {
                        throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222014.getCode(), String.format(WorkOrderErrorCodeEnum.API_ERROR_222014.getMsg(), robTypeStr));
                    }
                    params.put("corpid", corpid);
                    params.put("del", 0);
                    params.put("isNow", 1);
                    params.put("userIdIn", userIdList);
                    params.put("statusIn", Arrays.asList(WorkOrderNodeStatusEnum.UNACCEPTED.getCode(), WorkOrderNodeStatusEnum.ONGOING.getCode()));
                    params.put("groupByStr", "user_id");
                    params.put("orderByStr", "count(*) asc");
                    List<String> nodeUserIdList = workOrderFlowNodeModel.getUserIdList(params);
                    userIdList.removeAll(nodeUserIdList);
                    if (userIdList.isEmpty()) {
                        userId = nodeUserIdList.get(0);
                    } else {
                        userId = userIdList.get(0);
                    }
                    userEntity = userModel.getByKey(userId, corpid);
                    if (userEntity == null) {
                        throw new XbbException(WorkOrderErrorCodeEnum.API_ERROR_222027);
                    }
                    workOrderFlowNodeEntity = createNormalNode(workOrderId,expectedTime,userEntity,workOrderStageEntity);
                    pushIdList.add(userId);
                    break;
                case ROB:
                    isRob = true;
                    //如果是抢单就先生成节点，待人抢单后更新node数据
                    workOrderFlowNodeEntity = createRobNode(workOrderEntity, expectedTime,workOrderStageEntity);
                    switch (workOrderStageRobTypeEnum) {
                        case USER:
                            break;
                        case SERVICE:
                            pushIdList.addAll(getServiceUserIdList(corpid, workOrderStageEntity.getRefRobId()));
                            break;
                        case DEPARTMENT:
                            pushIdList.addAll(getDepartmentUserIdList(corpid, workOrderStageEntity.getRefRobId()));
                            break;
                        default:
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                    break;
                default:
                    //选择了人
                    userEntity = new UserEntity();
                    BeanUtil.copyProperties(workOrderStageEntity,userEntity);
                    userEntity.setUserId(workOrderStageEntity.getRefRobId());
                    userEntity.setAvatar(workOrderStageEntity.getUserAvatar());
                    userEntity.setName(workOrderStageEntity.getRefRobName());
                    userEntity.setCorpid(workOrderStageEntity.getCorpid());
                    workOrderFlowNodeEntity = createNormalNode(workOrderId,expectedTime,userEntity,workOrderStageEntity);
                    pushIdList.add(workOrderStageEntity.getRefRobId());
                    userId = workOrderStageEntity.getRefRobId();
            }
        }

        return new CreateNodeReturnPojo(pushIdList, userId, workOrderFlowNodeEntity, isRob);
    }

    private List<String> getServiceUserIdList(String corpid, String refRobId) {
        List<String> userIdList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("tagIdJsonLike", Long.valueOf(refRobId));
        param.put("del", 0);
        List<WorkOrderPersonEntity> personEntityList = workOrderPersonModel.findEntitys(param);
        for (WorkOrderPersonEntity entity : personEntityList) {
            userIdList.add(entity.getUserId());
        }
        return userIdList;
    }

    private List<String> getDepartmentUserIdList(String corpid, String refRobId) {
        List<String> userIdList = new ArrayList<>();
        List<Long> userDepartmentList = Collections.singletonList(Long.valueOf(refRobId));
        //是否为全公司
        Boolean isTopDep = userDepartmentList.contains(1L);
        Set<Long> depSet = new HashSet<>();
        if (!isTopDep){
            depSet.addAll(departmentModel.getSubDepIdList(corpid, userDepartmentList));
        }
        if (isTopDep) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("del", 0);
            userIdList = userModel.getUserIds(param);
        } else {
            userIdList = userModel.getDepUserIdList(corpid, depSet);
        }
        return userIdList;
    }


    private WorkOrderFlowNodeEntity createNormalNode(Long workOrderId, Integer expectedTime, UserEntity userEntity, WorkOrderStageEntity workOrderStageEntity) throws XbbException{
        WorkOrderFlowNodeEntity workOrderFlowNodeEntity = new WorkOrderFlowNodeEntity();
        workOrderFlowNodeEntity.setCorpid(userEntity.getCorpid());
        workOrderFlowNodeEntity.setWorkOrderId(workOrderId);
        workOrderFlowNodeEntity.setUserId(userEntity.getUserId());
        workOrderFlowNodeEntity.setUserAvatar(userEntity.getAvatar());
        workOrderFlowNodeEntity.setUserName(userEntity.getName());
        workOrderFlowNodeEntity.setStatus(WorkOrderNodeStatusEnum.UNACCEPTED.getCode());
//        workOrderFlowNodeEntity.setSort(0);
        workOrderFlowNodeEntity.setIsNow(1);
        workOrderFlowNodeEntity.setExpectedTime(expectedTime);
        workOrderFlowNodeEntity.setActualTime(0);
        workOrderFlowNodeEntity.setStartTime(0L);
        workOrderFlowNodeEntity.setEndTime(0L);
        if (!Objects.isNull(workOrderStageEntity)){
            workOrderFlowNodeEntity.setStageId(workOrderStageEntity.getId());
            workOrderFlowNodeEntity.setStageName(workOrderStageEntity.getName());
        }
        Integer maxSort = getMaxSort(workOrderFlowNodeEntity.getWorkOrderId(),workOrderFlowNodeEntity.getStageId(),workOrderFlowNodeEntity.getCorpid());
        workOrderFlowNodeEntity.setSort(maxSort);
        return workOrderFlowNodeEntity;
    }

    /**
     * 新建抢单节点
     * @param workOrderEntity 工单
     * @param expectedTime 预计耗时
     * @param workOrderStageEntity 阶段
     */
    private WorkOrderFlowNodeEntity createRobNode(WorkOrderEntity workOrderEntity, Integer expectedTime, WorkOrderStageEntity workOrderStageEntity) throws XbbException{
        WorkOrderFlowNodeEntity workOrderFlowNodeEntity = new WorkOrderFlowNodeEntity();
        workOrderFlowNodeEntity.setCorpid(workOrderStageEntity.getCorpid());
        workOrderFlowNodeEntity.setWorkOrderId(workOrderEntity.getId());
        workOrderFlowNodeEntity.setUserId("");
        workOrderFlowNodeEntity.setUserAvatar("");
        workOrderFlowNodeEntity.setUserName("");
        workOrderFlowNodeEntity.setStageId(workOrderStageEntity.getId());
        workOrderFlowNodeEntity.setStageName(workOrderStageEntity.getName());
        workOrderFlowNodeEntity.setStatus(WorkOrderNodeStatusEnum.UNACCEPTED.getCode());
        Integer maxSort = getMaxSort(workOrderFlowNodeEntity.getWorkOrderId(),workOrderFlowNodeEntity.getStageId(),workOrderFlowNodeEntity.getCorpid());
        workOrderFlowNodeEntity.setSort(maxSort);
        workOrderFlowNodeEntity.setIsNow(1);
        workOrderFlowNodeEntity.setExpectedTime(expectedTime);
        workOrderFlowNodeEntity.setActualTime(0);
        workOrderFlowNodeEntity.setStartTime(0L);
        workOrderFlowNodeEntity.setEndTime(0L);
        //设置为抢单节点
        workOrderFlowNodeEntity.setRobId(workOrderStageEntity.getRefRobId());
        workOrderFlowNodeEntity.setRobType(workOrderStageEntity.getRefRobType());
        workOrderFlowNodeEntity.setNodeType(WorkOrderFlowNodeTypeEnum.ROB_NODE.getCode());

        //更新工单主表的type为抢单工单
//        workOrderEntity.setType(WorkOrderTypeEnum.ROB.getCode());
//        workOrderModel.save(workOrderEntity);

        return workOrderFlowNodeEntity;
    }

    /**
     * 获取最大排序值
     * @param workOrderId
     * @param stageId
     * @param corpid
     * @return
     */
    private Integer getMaxSort(Long workOrderId, Long stageId, String corpid) {
        WorkOrderFlowNodeEntity lastNode = workOrderFlowNodeModel.getLastNode(workOrderId,stageId,corpid);
        Integer maxSort = 0;
        if (Objects.nonNull(lastNode)){
            maxSort = lastNode.getSort() + 1;
        }
        return maxSort;
    }


    public Integer judgeWorkOrderAllOutBound(Long outstockId, Long workOrderId, String corpid, List<ProductSavePojo> productSavePojoList) throws XbbException {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("workOrderId", workOrderId);
        param.put("del", 0);
        // 拿到合同的所有产品
        List<WorkOrderProductEntity> workOrderProductEntityList = workOrderProductModel.findEntitys(param);
        Map<Long,Double> outstockNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean needMerge = false;
        for (ProductSavePojo productSavePojo : productSavePojoList){
            if (Objects.isNull(productSavePojo.getRefProductId())) {
                needMerge = true;
                break;
            }
        }
        for (ProductSavePojo productSavePojo : productSavePojoList){
            if (needMerge) {
                Double num = outstockNumMap.getOrDefault(productSavePojo.getId(), 0D);
                num = Arith.add(num, productSavePojo.getNum());
                outstockNumMap.put(productSavePojo.getId(),num);
            } else {
                Double num = outstockNumMap.getOrDefault(productSavePojo.getRefProductId(), 0D);
                num = Arith.add(num, productSavePojo.getNum());
                outstockNumMap.put(productSavePojo.getRefProductId(), num);
            }
        }
        List<WorkOrderProductEntity> updateList = new ArrayList<>();
        //新数据逻辑
        if (!needMerge) {
            Integer shipStatus = WorkOrderShipStatusEnum.EMPTY.getCode();
//            boolean shippedFlag = false;
            boolean unShippedFlag = false;
//            boolean deliveredFlag = false;
            int flag;
            for (WorkOrderProductEntity entity : workOrderProductEntityList) {
                Long key = entity.getId();

                // 已出库数量
                Double workOrderOutstockNum = Objects.isNull(entity.getOutstockNum()) ? 0D : entity.getOutstockNum();
                // 产品总数量
                Double productNum = Objects.isNull(entity.getProductNum()) ? 0D : entity.getProductNum();
                // 剩余未出
                Double unStockNum = Arith.sub(entity.getProductNum(), workOrderOutstockNum);
                // 当前出库
                Double amendNum = outstockNumMap.get(key);
                if (Objects.nonNull(amendNum)){
                    entity.setOutstockNum(Arith.add(amendNum,workOrderOutstockNum));
                }
                entity.setUpdateTime(DateTimeUtil.getInt());
                updateList.add(entity);
                // 改出库状态
                if (Objects.nonNull(amendNum)) {
                    flag = Arith.compare(amendNum, unStockNum);
                    if (flag != 0) {
                        unShippedFlag = true;
                        continue;
                    }
                } else {
                    if (!Objects.equals(unStockNum, 0D)) {
                        unShippedFlag = true;
                        continue;
                    }
                }

//                if (outstockNumMap.containsKey(key)) {
//                    // 已出库数量
//                    Double workOrderOutstockNum = Objects.isNull(entity.getOutstockNum()) ? 0D : entity.getOutstockNum();
//                    // 产品总数量
//                    Double productNum = Objects.isNull(entity.getProductNum()) ? 0D : entity.getProductNum();
//                    // 剩余未出
//                    Double unStockNum = Arith.sub(entity.getProductNum(), workOrderOutstockNum);
//                    // 当前出库
//                    Double amendNum = outstockNumMap.get(key);
//                    entity.setOutstockNum(amendNum);
//                    entity.setUpdateTime(DateTimeUtil.getInt());
//                    updateList.add(entity);
//                    // 改出库状态
//                    flag = Arith.compare(amendNum, unStockNum);
//                    if (flag == 0) { // 全部出库
//                        shipStatus = WorkOrderShipStatusEnum.SHIPPED.getCode();
//                        shippedFlag = true;
//                    }
//                    if (flag < 0) { // 部分出库
//                        shipStatus = WorkOrderShipStatusEnum.DELIVERED.getCode();
//                        deliveredFlag = true;
//                    }
//                } else {
//                    // 出库数量没有就是未出库
//                    shipStatus = WorkOrderShipStatusEnum.UNSHIPPED.getCode();
//                    unShippedFlag = true;
//                }
            }
            // 以下情况修改出库状态为部分出库
//            if ((shippedFlag && unShippedFlag) || deliveredFlag) {
//                shipStatus = WorkOrderShipStatusEnum.DELIVERED.getCode();
//            }
            if (unShippedFlag) {
                shipStatus = WorkOrderShipStatusEnum.DELIVERED.getCode();
            } else {
                shipStatus = WorkOrderShipStatusEnum.SHIPPED.getCode();
            }
            if (!updateList.isEmpty()) {
                workOrderProductModel.updateOutstockBatch(updateList,corpid);
            }
            return shipStatus;
        }else {
            //老数据逻辑
            Map<Long,Double> workOrderOutstockNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (WorkOrderProductEntity entity : workOrderProductEntityList) {
                Long key = entity.getProductId();
                Double num = workOrderOutstockNumMap.getOrDefault(entity.getProductId(), 0D);
                num = Arith.add(num, entity.getProductNum());
                workOrderOutstockNumMap.put(entity.getProductId(), num);
                if (outstockNumMap.containsKey(key)) {
                    // 剩余未出
                    Double unStockNum = Arith.sub(entity.getProductNum(), entity.getOutstockNum());
                    // 当前出库
                    Double amendNum = outstockNumMap.get(key);
                    // 当前应出，包含超发的情况
                    Double outstockNum;
                    double outNum = Arith.sub(amendNum, unStockNum);
                    if (outNum > 0) {
                        outstockNum = entity.getProductNum();
                        outstockNumMap.put(key, outNum);
                    }else {
                        outstockNum = Arith.add(entity.getOutstockNum(), amendNum);
                        outstockNumMap.remove(key);
                    }
                    entity.setOutstockNum(outstockNum);
                    entity.setUpdateTime(DateTimeUtil.getInt());
                    updateList.add(entity);
                }
            }
            if (!updateList.isEmpty()) {
                workOrderProductModel.updateBatch(updateList,corpid);
            }
            boolean allOutBound = saasProductHelp.judgeAllOutBound(workOrderOutstockNumMap, workOrderId, OutstockTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), corpid, productSavePojoList, outstockId);
            if (allOutBound) {
                return WorkOrderShipStatusEnum.SHIPPED.getCode();
            }
            return WorkOrderShipStatusEnum.DELIVERED.getCode();
        }
    }



}
